/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
 */

import path from 'path';

import { cloneDeep } from '@baize/wdk';
import fse from 'fs-extra';

import { hash } from '@ohos/hvigor-common';
import { PathUtil } from '../../../common/util/path-util.js';
import { replacer } from '../../../common/util/replacer.js';

/**
 * 打点管理
 */
export class TraceManager {
  private readonly data: Record<string, any>;
  private callBackList: Record<string, Function> = {};

  constructor() {
    this.data = {};
    this.callBackList = {};
  }

  /**
   * 记录数据, 以项目为单位
   * @param {string} key 项目名
   * @param data 打点数据
   * @param {Function} callback 回调，会在落盘后执行
   */
  public trace(key: string, data: any, callback?: Function) {
    this.data[key] = data;
    if (typeof callback === 'function') {
      this.callBackList[key] = callback;
    }
  }

  /**
   * 将打点数据落盘：.hvigor/outputs/logs/details/details.json
   */
  flush(): void {
    // 拷贝数据，执行回调
    const data = cloneDeep(this.data);
    for (const key in this.callBackList) {
      this.callBackList[key]();
    }

    // 落盘
    const detailsDir = path.resolve(PathUtil.getHvigorCacheDir(), './outputs/logs/details');
    const detailsJson = path.resolve(detailsDir, 'details.json')
    fse.ensureDirSync(detailsDir);
    try {
      fse.writeFileSync(detailsJson, JSON.stringify(data, replacer, 2));
    } catch (e) {
      // 打点数据文件创建失败-不用处理
    }
  }

  /**
   * 打点数据的key值不能有'.'
   * @param {string} key
   * @returns {string}
   */
  static transformKey(key: string) {
    return key.replace(/\./g, '_');
  }

  /**
   * 对字符串匿名化处理
   * @param {string} str
   * @returns {string}
   */
  static anonymize(str: string): string {
    return hash(str);
  }

  public static trace(key: string, data: any, callback?: Function) {
    traceManager.trace(key, data, callback);
  }
}

export const traceManager = new TraceManager();
